from Products.Five import BrowserView
from Products.CMFCore.utils  import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.CMFCore.permissions import ReviewPortalContent
from Products.CMFPlone.utils import base_hasattr
from Products.ePubBook.interfaces import IShelf
from plone.app.layout.navigation.interfaces import INavigationRoot
import json
from DateTime.DateTime import DateTime
from Products.PlonePAS.utils import cleanId
class GotoShelf():
    def __init__(self,context,request):
        self.context = context
        self.request = request
    def __call__(self):
        mt = getToolByName(self, 'portal_membership')
        homeuid = cleanId( mt.getAuthenticatedMember().getId() )
    
        isCreated = self.context.hasObject(homeuid)
        if not isCreated:
            self.context.invokeFactory("EpubShelf",homeuid)
            shelf = getattr(self.context,homeuid)
            shelf.invokeFactory("App","app")
        self.request.RESPONSE.redirect(self.context.absolute_url()+'/myshelf')
    
class IndexView(BrowserView):
    def __init__(self, context, request):
        self.context = context
        BrowserView.__init__(self, context, request)
    def path(self):
        mt = getToolByName(self, 'portal_membership')
        homeuid = cleanId( mt.getAuthenticatedMember().getId() )
        return '/'.join(self.context.getPhysicalPath())+'/'+homeuid
    def review_state(self):
        shelf = self.context.restrictedTraverse(self.path())
        app   = self.context.restrictedTraverse(self.path()+'/app')
        shelf_review_state = self.context.portal_workflow.getInfoFor(shelf,'review_state')
        if shelf_review_state == 'private':
            return 'private'
        app_review_state   = self.context.portal_workflow.getInfoFor(app,'review_state')
        if shelf_review_state == 'published' and app_review_state=='published':
            return 'published'
        else:
            return 'pending'
class CheckShelf(BrowserView):
    """Shelf CheckView
    """
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
        
class PayView(BrowserView):
    """Shelf PayView
    """
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
class InfoView(BrowserView):
    """Shelf info view baseview
    """
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
       
class IdsJson():
    """ shelfids for public
    """
    def __init__(self,context,request):
        self.context = context
        self.request = request
    def __call__(self):
        result = {}
        items = None
        path  = '/'.join(self.context.getPhysicalPath())
        if IShelf.providedBy(self.context): # For bookshelf
            if base_hasattr(self.request, 'updated'):
                try:
                    updated = self.request.updated
                    date = DateTime(updated)
                    items = self.context.portal_catalog.searchResults(path=path,Type="EpubBook",modified = {"query": date, "range": "min"},review_state='published',sort_on='modified',sort_order='descending')
                except:
                    return '{"Status":"Error","Message":"format updated error %s","Result":"[]"}' % self.request.updated 
            else:
                items = self.context.portal_catalog.searchResults(path=path,Type="EpubBook",review_state='published',sort_on='modified',sort_order='descending')
            
        
        elif INavigationRoot.providedBy(self.context): # For  epub360
            if base_hasattr(self.request, 'updated'):
                try:
                    updated = self.request.updated
                    date = DateTime(updated)
                    items = self.context.portal_catalog.searchResults(path=path,Type="EpubBook",getIsinsite=True,modified = {"query": date, "range": "min"},review_state='published',sort_on='modified',sort_order='descending')
                except:
                    return '{"Status":"Error","Message":"format updated error %s","Result":"[]"}' % self.request.updated 
            else:
                items = self.context.portal_catalog.searchResults(path=path,Type="EpubBook",getIsinsite=True,review_state='published',sort_on='modified',sort_order='descending')
        else:
            return '{"Status":"Error","Message":"Only for bookshelf","Result":"[]"}'
        ids = []
        for item in items:
            ids.append(item.UID)
        result['Status'] = 'Success'
        result['Result'] = ids
        return json.dumps(result)

class MyShelfIds():
    """ shelf ids for test
    """
    def __init__(self,context,request):
        self.context = context
        self.request = request
    def __call__(self):
        result = {}
        mt = getToolByName(self.context, 'portal_membership')
        
        if mt.isAnonymousUser():
            return '{"Status":"Error","Message":"Please login first "}'
        results = None
        isReviewer = False
        if mt.checkPermission(ReviewPortalContent, self.context):
            ###
            path ='/'.join(self.context.getPhysicalPath())+'/Members'
            results = self.context.portal_catalog.searchResults(path=path,Type="EpubBook")
            isReviewer = True
        else:
            mt = getToolByName(self, 'portal_membership')
            homeuid = cleanId( mt.getAuthenticatedMember().getId() )
                  
            path ='/'.join(self.context.getPhysicalPath())+'/bookshelf/'+homeuid
            
            results = self.context.portal_catalog.searchResults(path=path,Type="EpubBook",sort_on='modified',sort_order='descending')
            
        ids = []
        for item in results:
            if isReviewer:
                 review_state = item.review_state
                 if (review_state in ('unpaid','rejected','paid','checkpaid') ):
                     continue
            ids.append(item.UID)
                
        result['Status'] = 'Success'
        result['Result'] = ids
        return json.dumps(result)
        